﻿using AixCommInfo;
using ISaveReaddll;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security.RightsManagement;
using System.Text;
using System.Threading.Tasks;
using System.Windows;


namespace WpfZMotion_FinalTestMachine.Core.AWB
{
   public  class AWBHelper : BindableObject
    {
        public AWBHelper(SerialPortDemo3.ConnectSerialPortHelper serialPortHelper, Func<string> readPath)
        {
            AWBClient = serialPortHelper;
            AWBClient.RecevieBytesActionEventHander += ReceiveData;
            SaveRead = new SaveReaddll.SaveReadHeler(readPath, () => this);
            Read();
        }
       
        private void ReceiveData(byte[] bytes)
        {
            try
            {
                Console.WriteLine(bytes);
                // 将字节转换为整数  
                AWBValue = GetintData(bytes[3], bytes[4]).ToString();

                AWBData  = GetintData(bytes[5], bytes[6]).ToString();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }

        }

        SerialPortDemo3.ConnectSerialPortHelper AWBClient;

        public string _data = string.Empty;
        public string _value = string.Empty;
        SaveReaddll.SaveReadHeler SaveRead;

        public void Read()
        {
            SaveRead?.Read();
        }

        public void Save()
        {
            SaveRead?.Save();
        }
        [SaveRemark]
        public string AWBData
        {
            get { return _data; }
            set { SetProperty(ref _data, value); }
        }
        [SaveRemark]
        public string AWBValue
        {
            get { return _value; }
            set { SetProperty(ref _value, value); }
        }
        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="data">色温</param>
        /// <param name="value">数值</param>
        /// <param name="error"></param>
        /// <returns></returns>
        public bool WriteData(string data)
        {
            //数据格式
            //data = "55,AA,01,54,0B,00,00"
            //0为低字节，1为高位字节。色温，照度字节
            string[] Data_HexArray = new string[2];
           
            int intDecData = 0;
            if (int.TryParse(data, out intDecData))
            {
                //X表示转换为大写的十六进制，4表示自动补全4位
                var Hexstring = intDecData.ToString("X4");
                //转换的低字节
                Data_HexArray[0] = Hexstring.Substring(2, 2);
                //转换的高位字节
                Data_HexArray[1] = Hexstring.Substring(0, 2);
            }
            else
            {
                return false;
            }
            if (!string.IsNullOrEmpty(Data_HexArray[0]) )
            {
                var Command_WriteData = "55 AA 01 " + Data_HexArray[0] + " " + Data_HexArray[1] +" 00 00";
                ReadData(Command_WriteData);
            }
            return true;
        }
        public bool WriteData(string data, out string error)
        {
            //数据格式
            //data = "55,AA,01,54,0B,00,00"
            //0为低字节，1为高位字节。色温，照度字节
            string[] Data_HexArray = new string[2];

            int intDecData = 0;
            if (int.TryParse(data, out intDecData))
            {
                //X表示转换为大写的十六进制，4表示自动补全4位
                var Hexstring = intDecData.ToString("X4");
                //转换的低字节
                Data_HexArray[0] = Hexstring.Substring(2, 2);
                //转换的高位字节
                Data_HexArray[1] = Hexstring.Substring(0, 2);
            }
            else
            {
                error = "AWB色温数值格式不正确";
                return false;
            }
            if (!string.IsNullOrEmpty(Data_HexArray[0]))
            {
                var Command_WriteData = "55 AA 01 " + Data_HexArray[0] + " " + Data_HexArray[1] + " 00 00";
                ReadData(Command_WriteData);
            }
            else
            {
                error = "待写入数据为空！";
            }
            error = "";
            return true;
        }
        public bool WriteValue(string value, out string error)
        {
            string[] Value_HexArray = new string[2];
            int intDecData = 0;
            if (int.TryParse(value, out intDecData))
            {
                //X表示转换为大写的十六进制，4表示自动补全4位
                var Hexstring = intDecData.ToString("X4");
                //转换的低字节
                Value_HexArray[0] = Hexstring.Substring(2, 2);
                //转换的高位字节
                Value_HexArray[1] = Hexstring.Substring(0, 2);
            }
            if (!string.IsNullOrEmpty(Value_HexArray[0]))
            {
                var Command_WriteValue = "55 AA 02 " + Value_HexArray[0] + " " + Value_HexArray[1] + " 00 00";
                ReadData(Command_WriteValue);
            }
            error = "";
            return true;
        }
        public bool WriteValue(string value)
        {
            string[] Value_HexArray = new string[2];
            int intDecData = 0;
            if (int.TryParse(value, out intDecData))
            {
                //X表示转换为大写的十六进制，4表示自动补全4位
                var Hexstring = intDecData.ToString("X4");
                //转换的低字节
                Value_HexArray[0] = Hexstring.Substring(2, 2);
                //转换的高位字节
                Value_HexArray[1] = Hexstring.Substring(0, 2);
            }
            if (!string.IsNullOrEmpty(Value_HexArray[0]))
            {
                var Command_WriteValue = "55 AA 02 " + Value_HexArray[0] + " " + Value_HexArray[1] + " 00 00";
                ReadData(Command_WriteValue);
            }
            return true;
        }
        /// <summary>
        /// 发送命令
        /// </summary>
        /// <param name="command"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public bool SendCommand(string command,out string error)
        {
            //发送数据
            error = string.Empty;
            for (int i = 0; i < 3; i++)
            {
                try
                {
                    System.Threading.Thread.Sleep(100);
                    AWBClient.SendBytes(stringToHex(command));
                    System.Threading.Thread.Sleep(200);
                    return true;
                }
                catch (Exception e)
                {
                    if (i == 2)
                    {
                        error = e.Message;
                        return false;
                    }
                    System.Threading.Thread.Sleep(200);
                }
            }
            error = "AWB写入超时";
            return false;
        }
        //接收数据  "55,AA,00,00,00,00,00"
        /// <summary>
        /// duqu
        /// </summary>
        /// <param name="command_read"></param>
        public void ReadData(string Command_Read = "55 AA 00 00 00 00 00")
        {
            string error;
           var Hexstring8 = " " + GetLastByte(Command_Read);
            Command_Read += Hexstring8;
            SendCommand(Command_Read, out error);
        }

        /// <summary>
        /// 将十六进制字符串转换为十进制字节数组
        /// </summary>
        /// <param name="hexstring"></param>
        public  byte[] stringToHex(string hexstring)
        {
            Console.WriteLine(hexstring);
            byte[] bytesToSend = hexstring.Split(' ').Select(hex => Convert.ToByte(hex, 16)).ToArray();
            return bytesToSend;
        }
        /// <summary>
        /// 十进制字符串转十六进制字符串
        /// </summary>
        /// <param name="decstring"></param>
        /// <returns></returns>
        public  string[] DecToHex(string decstring)
        {
            try
            {
                //0为低字节，1为高位字节
                string[] HexArray = new string[2];
                int intDec = 0;
                if (int.TryParse(decstring, out intDec))
                {
                    //X表示转换为大写的十六进制，4表示自动补全4位
                    var Hexstring = intDec.ToString("X4");
                    //转换的低字节
                    HexArray[0] = Hexstring.Substring(2, 2);
                    //转换的高位字节
                    HexArray[1] = Hexstring.Substring(0, 2);
                }

                return HexArray;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
                return null;
            }
           
        }
        /// <summary>
        /// 获取校验字,第八位
        /// </summary>
        /// <param name="stringbytes"></param>
        /// <returns></returns>
        public  string GetLastByte(string stringbytes)
        {
           var HexArray2 = stringToHex(stringbytes);
            byte data = SumAndComplement(HexArray2);
            var Hexstring8 = data.ToString("X2");
            return Hexstring8;
        }
        /// <summary>
        /// 校验字算法:byte0~byte6 累加和 低 8 位取反 为 byte7 的内容
        /// </summary>
        /// <param name="hexBytes"></param>
        /// <returns></returns>
        public  byte SumAndComplement(byte[] hexBytes)
        {
            try
            {
                // 检查字节数组长度是否为7
                if (hexBytes.Length != 7)
                {
                    throw new ArgumentException("The array must contain exactly 7 bytes.");
                }

                // 计算总和（按位与运算确保正数）
                byte sum = 0;
                foreach (byte b in hexBytes)
                {
                    sum += b;
                }

                // 取反（按位异或运算）
                return (byte)(sum ^ 0xFF); // 取反并限制在0-255范围内，相当于总和模256取余操作。
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString()); return 0;
            }  
        }
        //高低十进制字节转十六进制函数
        public int GetintData(byte low,byte hight)
        {
            try
            {
                int aa = BitConverter.ToInt16(new byte[] { low,hight},0); 
                //var HEXstr = hight.ToString("X") + low.ToString("X");
                //int aa = Convert.ToInt32(HEXstr, 16);
                return aa;
            }
            catch(Exception EX)
            {
                MessageBox.Show(EX.Message);
                return 0;
            }
           
        }
    }
}
